package com.simple.pixelcopydemo

import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Rect
import android.graphics.SurfaceTexture
import android.media.MediaPlayer
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.PixelCopy
import android.view.Surface
import android.view.TextureView
import android.widget.Button
import android.widget.ImageView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.graphics.createBitmap
import androidx.core.net.toUri
import androidx.core.view.drawToBitmap
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class TextureViewActivity : AppCompatActivity() {
    private lateinit var textureView: TextureView
    private lateinit var mediaPlayer: MediaPlayer

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_texture_view)

        textureView = findViewById(R.id.texture_view)
        val button = findViewById<Button>(R.id.btn_capture)

        textureView.surfaceTextureListener = object : TextureView.SurfaceTextureListener {
            override fun onSurfaceTextureAvailable(surface: SurfaceTexture, w: Int, h: Int) {
                mediaPlayer = MediaPlayer().apply {
                    val uri =
                        "https://www.learningcontainer.com/wp-content/uploads/2020/05/sample-mp4-file.mp4".toUri()

                    setDataSource(this@TextureViewActivity, uri)
                    setSurface(Surface(surface))
                    isLooping = true
                    prepareAsync()
                    setOnPreparedListener { start() }
                }
            }

            override fun onSurfaceTextureDestroyed(surface: SurfaceTexture) = true
            override fun onSurfaceTextureSizeChanged(s: SurfaceTexture, w: Int, h: Int) {}
            override fun onSurfaceTextureUpdated(surface: SurfaceTexture) {}
        }

        button.setOnClickListener {
//            val view=window.decorView.rootView
//            view.drawToBitmap()
//            val bitmap = Bitmap.createBitmap(view.width, view.height, Bitmap.Config.RGB_565)
//            val canvas = Canvas(bitmap)
//            view.draw(canvas)

            val view = window.decorView.rootView
            view.isDrawingCacheEnabled = true
            val bitmap = Bitmap.createBitmap(view.drawingCache)
            view.isDrawingCacheEnabled = false
            lifecycleScope.launch(IO) {
                val bitmap = copyBitmapFromWindow()
                bitmap?.let {
                    withContext(Dispatchers.Main) {
                        showBitmap(it)
                    }

                }

            }

        }
    }

    private fun showBitmap(bitmap: Bitmap) {
        val imageView = ImageView(this).apply { setImageBitmap(bitmap) }
        AlertDialog.Builder(this).setTitle("截图").setView(imageView).setPositiveButton("关闭", null).show()
    }

    private suspend fun copyBitmapFromWindow(): Bitmap? =
        withContext(IO) {
            val bitmap =
                createBitmap(window.decorView.width, window.decorView.height, Bitmap.Config.RGB_565)
            val result = CompletableDeferred<Bitmap?>()
            val rect = Rect(100, 100, 30000, 30000)
            /**
             * 可以获取TextureView加载的视频截图,不能获取SurfaceView加载的视频截图
             * window:截图的窗口,不能为空
             * rect:截图区域，相对于 window 的位置坐标（非屏幕坐标）,可以为空,为空就是整个window的大小
             * bitmap:用来接收截图的 Bitmap,不能为空
             * handler:处理截图结果回调的线程，一般用 MainLooper
             */
            PixelCopy.request(window,rect, bitmap, { copyResult ->
                if (copyResult == PixelCopy.SUCCESS) {
                    result.complete(bitmap)
                } else {
                    result.complete(null)
                }
            }, Handler(Looper.getMainLooper()))
            result.await() // 等待结果
        }
}
